#include "audioplayer.h"
#include <QFile>

AudioPlayer::AudioPlayer(QObject *parent) :
    QObject(parent)
{
    m_audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);
    m_mediaObject = new Phonon::MediaObject;
    m_mediaObject->setTransitionTime(3000);
    Phonon::createPath(m_mediaObject, m_audioOutput);

    connect(m_mediaObject, SIGNAL(stateChanged(Phonon::State,Phonon::State)),
            this, SLOT(stateChanged(Phonon::State,Phonon::State)));

}

void AudioPlayer::addAudio(const QString &fileName)
{
    if (fileName.isEmpty()) {
        qWarning() << "AudioPlayer::addAudio(): empty file name";
        return;
    }

    if (!QFile(fileName).exists()) {
        qWarning() << "AudioPlayer::addAudio(): file" << fileName << "doesn't exist!";
        return;
    }

    Phonon::MediaSource source(fileName);
    qDebug() << "Source:" << fileName;
    if (m_mediaObject->state() == Phonon::PlayingState) {
        m_mediaObject->enqueue(source);
        qDebug() << "enqueue!";
    } else {
        m_mediaObject->setCurrentSource(source);
        qDebug() << "setCurrent...!";
    }
    m_mediaObject->play();
}

void AudioPlayer::stateChanged(Phonon::State oldState, Phonon::State newState)
{
    switch (newState) {
    case Phonon::ErrorState:
        if (m_mediaObject->errorType() == Phonon::FatalError) {
            qWarning() << "AudioPlayer: fatal" << m_mediaObject->errorString();
        } else {
            qDebug() << "AudioPlayer: non fatal" << m_mediaObject->errorString();
        }
        break;

    case Phonon::PlayingState:
        qDebug() << "AudioPlayer: playing:" << m_mediaObject->currentSource().fileName();
        break;
    case Phonon::StoppedState:
        qDebug() << "AudioPlayer: stopped";
        break;
    case Phonon::PausedState:
        break;
    case Phonon::BufferingState:
        break;
    default:
        ;
    }

    /*if (newState != Phonon::StoppedState && newState != Phonon::PausedState) { // play?
        qWarning() << "AudioPlayer:" << "? stopped || paused" << m_mediaObject->currentSource().fileName();
        return;
    }*/

    if (m_mediaObject->currentSource().type() == Phonon::MediaSource::Invalid) {
        qWarning() << "AudioPlayer:" << "invalid source:" << m_mediaObject->currentSource().fileName();
        return;
    }


}
